package gitlab

import (
	"crypto/tls"
	"errors"
	"net/http"
	"time"

	"github.com/parnurzeal/gorequest"

	"chainmaker.org/chainmaker/smarteditor/conf"
	"chainmaker.org/chainmaker/smarteditor/logger"
)

var log = logger.Get()

// GetUserInfo query GitLab user info.
func GetUserInfo(authorizationCode, redirectUrl string) (map[string]interface{}, error) {
	token, err := getToken(authorizationCode, redirectUrl)
	if err != nil {
		return nil, err
	}

	result := map[string]interface{}{}
	response, data, errs := gorequest.New().
		TLSClientConfig(&tls.Config{InsecureSkipVerify: true}).
		Get(conf.Wide.GitLabOAuthServer+"/api/v4/user").
		AppendHeader("Authorization", "Bearer "+token).
		Timeout(5 * time.Second).
		EndStruct(&result)
	if nil != errs || http.StatusOK != response.StatusCode {
		log.Errorf("[GetUserInfo] get user info failed: %v, %s", err, data)
		return nil, errors.New("get user info failed")
	}
	return result, nil
}

//getToken get GitLab token
func getToken(authorizationCode, redirectUrl string) (string, error) {
	result := map[string]interface{}{}
	response, data, errs := gorequest.New().
		TLSClientConfig(&tls.Config{InsecureSkipVerify: true}).
		Post(conf.Wide.GitLabOAuthServer + "/oauth/token").
		SendString("code=" + authorizationCode).
		SendString("client_id=" + conf.Wide.GitLabClientId).
		SendString("client_secret=" + conf.Wide.GitLabClientSecret).
		SendString("grant_type=authorization_code").
		SendString("redirect_uri=" + redirectUrl).
		Timeout(5 * time.Second).
		EndStruct(&result)

	if nil != errs || http.StatusOK != response.StatusCode {
		log.Errorf("[getToken] get token failed: %+v, %s", errs, data)
		return "", errors.New("get token failed")
	}
	return result["access_token"].(string), nil
}
